package run;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;


/**
 * Created by v on 17-7-11.
 * 把提交上来的代码写入到文件中
 */
public class Call {
    private static final String path="/home/v/code/";

    //生成需要java源代码文件
    private static boolean generateFile(String ip,String code){
        try {

            File file=new File(path+ip);
            if(!file.exists()){
                file.mkdir();
            }
            file=new File(path+ip+"/Main.java");
            if(file.exists()){
                file.delete();
            }
            file.createNewFile();

            //把代码写入到文件中
            PrintWriter output=new PrintWriter(file);
            output.write(code);
            output.close();
        }catch (IOException ex){
            ex.printStackTrace();
            return false;
        }

        return true;
    }

    //编译并执行java的源代码程序，完成以后返回执行结果
    private static String run(String ip){
        StringBuffer buffer=new StringBuffer();
        Scanner input;

        try {
            Process ps=Runtime.getRuntime().exec("javac "+path+ip+"/Main.java");
            ps.waitFor();

            input=new Scanner(ps.getErrorStream());
            boolean error=false;
            while (input.hasNext()){
                buffer.append(input.nextLine()+"\n");
                error=true;
            }

            if(error){
                return buffer.toString();
            }

            //调用shell赋予文件可执行权限
            ps=Runtime.getRuntime().exec("chmod 777 "+path+ip+"/Main.class");
            ps.waitFor();

            //执行该文件并把执行的结果收集起来
            ps=Runtime.getRuntime().exec("java -cp "+path+ip+"/ Main");
            ps.waitFor();

            input=new Scanner(ps.getInputStream());
            while (input.hasNext()){
                buffer.append(input.nextLine()+"\n");
            }
        }catch (Exception ex){
            buffer.append("发生了可怕的系统异常，请赶紧联系攻城狮！");
        }

        return buffer.toString();
    }

    //调用入口
    public static String call(String code,String ip){
        String string;
        if(!generateFile(ip,code)){
            string="发生了系统错误，请赶快练习攻城狮！";
            return string;
        }

        string=run(ip);
        return string;
    }
}
